package ru.inse.core.service.realty.impl;

import ru.inse.core.common.listeners.IEventListener;
import ru.inse.core.common.listeners.ListenerContainer;
import ru.inse.core.dao.DaoException;
import ru.inse.core.dao.IDao;
import ru.inse.core.dao.realty.IRealtyItemCriteraAppenderFactory;
import ru.inse.core.dao.realty.IRealtyItemDao;
import ru.inse.core.dao.realty.RealtyQueryParam;
import ru.inse.core.domain.realty.RealtyItem;
import ru.inse.core.domain.realty.RealtyObject;
import ru.inse.core.domain.realty.RealtyRubric;
import ru.inse.core.service.AbstractService;
import ru.inse.core.service.realty.IRealtyItemService;


final public class RealtyItemService
    extends AbstractService<RealtyItem>
    implements IRealtyItemService
{
    private IRealtyItemDao dao;
    private IRealtyItemCriteraAppenderFactory appenderFactory;
    private ListenerContainer<RealtyItemChangedEvent> listenerContainer;


    public void setRealtyItemDao(IRealtyItemDao dao)
    {
        this.dao = dao;
    }
    
    private RealtyItemService()
    {
        listenerContainer = new ListenerContainer<RealtyItemChangedEvent>();
    }

    public void addItemListener(IEventListener<RealtyItemChangedEvent> listener)
    {
        listenerContainer.add(listener);
    }

    public IRealtyItemCriteraAppenderFactory getAppenderFactory()
    {
        return appenderFactory;
    }

    public void setAppenderFactory(IRealtyItemCriteraAppenderFactory appenderFactory)
    {
        this.appenderFactory = appenderFactory;
    }
    
    @Override
    protected IDao<RealtyItem> getDao()
    {
        return dao;
    }

    public void persist(RealtyItem item, Long cityId)
        throws RealtyServiceException, DaoException
    {
        //        User currentUser = SecurityManager.getInstance().getCurrentUser();
        //        if (currentUser == null)
        //        {
        //            throw new RealtyManagerException(RealtyManagerException.IDS_USER_IS_NOT_SPECIFIED);
        //        }
        //        setGuestIfUserIsNull(item);
        listenerContainer.notify(RealtyItemChangedEvent.newInstance(
            RealtyItemChangedEvent.EventType.BEFORE_INSERT, item, cityId));
        getDao().persist(item);
        listenerContainer.notify(RealtyItemChangedEvent.newInstance(
            RealtyItemChangedEvent.EventType.AFTER_INSERT, item, cityId));
    }

    public void save(RealtyItem item, Long cityId)
        throws RealtyServiceException, DaoException
    {
        //        if (!SecurityManager.getInstance().assertAdminOrCurrentUser(item.getUser().getId()))
        //        {
        //            throw new RealtyManagerException(
        //                RealtyManagerException.IDS_CURRENT_USER_IS_NOT_EQUALS_TO_FLAT_CREATER);
        //        }
        listenerContainer.notify(RealtyItemChangedEvent.newInstance(
            RealtyItemChangedEvent.EventType.BEFORE_UPDATE, item, cityId));
        getDao().save(item);
        listenerContainer.notify(RealtyItemChangedEvent.newInstance(
            RealtyItemChangedEvent.EventType.AFTER_UPDATE, item, cityId));
    }

    public void remove(Long id, Long cityId)
        throws DaoException
    {
        RealtyItem item = getById(id);
        listenerContainer.notify(RealtyItemChangedEvent.newInstance(
            RealtyItemChangedEvent.EventType.BEFORE_DELETE, item, cityId));
        //TODO Удалить картинки
        dao.remove(id);
        listenerContainer.notify(RealtyItemChangedEvent.newInstance(
            RealtyItemChangedEvent.EventType.AFTER_DELETE, item, cityId));
    }
    
    
    public Long count(RealtyQueryParam param, RealtyRubric rubric, RealtyObject object)
    {
        return count(appenderFactory.createCriteriaAppender(rubric, object, param));
    }

    
    /**
     * Возвращает список квартир используя апендер критерий
     * @param roomCount
     * @return
     * @throws CoreException 
     */
    //    public ResultContainer<RealtyItem> findPage(final RealtyQueryParam param,
    //        final ICriteriaAppender [] criteriaAppenders, final Boolean fillPagingInfo)
    //        throws CoreException
    //    {
    //        ResultContainer<RealtyItem> result = dao.findPage(param, criteriaAppenders);
    //        if (fillPagingInfo)
    //        {
    //            result.setPagingInfo(getPagingInfo(param, criteriaAppenders));
    //        }
    //        return result;
    //    }
    /**
     * Возвращает список картинок фаворитов для квартир
     * @param resourceBasePath
     * @param sectionPathPiece
     * @param flats
     * @return
     * @throws ResourceFileSuiteException
     */
    //    public Map<Long, String> getFavoritImageUrl(String resourceBasePath, String sectionPathPiece,
    //        List<RealtyItem> flats)
    //        throws ResourceFileSuiteException
    //    {
    //        //TODO Добавить кеширование   
    //        ImageUploadResourceManager imageUploadResourceManager = new ImageUploadResourceManager(
    //            resourceBasePath, sectionPathPiece);
    //        return imageUploadResourceManager.getFavoritImageUrl(flats);
    //    }
    /**
     * Сохраняет картинку для квартиры
     * @param resourceBasePath
     * @param sectionPathPiece
     * @param item
     * @param file
     * @throws ResourceFileSuiteException
     * @throws ImageConvertException 
     * @throws RealtyManagerException 
     */
    //    public void saveImage(String resourceBasePath, String sectionPathPiece, RealtyItem item,
    //        InputStream is, String contentType, float scaleToSize)
    //        throws ResourceFileSuiteException, ImageConvertException, RealtyManagerException
    //    {
    //        if (!SecurityManager.getInstance().assertAdminOrCurrentUser(item.getUser().getId()))
    //        {
    //            throw new RealtyManagerException(
    //                RealtyManagerException.IDS_CURRENT_USER_IS_NOT_EQUALS_TO_FLAT_CREATER);
    //        }
    //        ImageUploadResourceManager imageUploadResourceManager = new ImageUploadResourceManager(
    //            resourceBasePath, sectionPathPiece);
    //        imageUploadResourceManager.saveImage(is, contentType, item.getId(), scaleToSize);
    //    }
    //
    //    private void setGuestIfUserIsNull(RealtyItem item)
    //        throws DaoException
    //    {
    //        User user = item.getUser();
    //        if (user == null)
    //        {
    //            item.setUser(SecurityManager.getInstance().getCurrentUserOrGuest());
    //        }
    //    }
}
